<template>
	<div v-if="dialogData.isShow">
		<el-dialog width="500px" :model-value="true" destroy-on-close :title="dialogData.title" @close="closeDialog">
			<el-form ref="formRef" :rules="rules" :model="form" label-width="90px">
				<el-row>
					<el-col>
						<el-form-item label="资源名称" prop="name">
							<el-input v-model="form.name" placeholder="请输入资源名称" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="版本" prop="version">
							<el-input v-model="form.version" placeholder="请输入版本" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="类别名称">
							<el-select v-model="form.resourceTypeCode" disabled>
								<el-option v-for="item in typeList" :key="item.code" :label="item.name" :value="item.code" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="年级" prop="grade">
							<el-input v-model="form.grade" placeholder="请输入年级" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="班别" prop="className">
							<el-input v-model="form.className" placeholder="请输入班别" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="文件">
							<el-upload class="upload-demo" :http-request="handleUpload" :before-upload="beforeUpload" :limit="1" :on-exceed="handleExceed">
								<el-button v-auth="'sys:resource:upload'" type="primary">点击上传</el-button>
								<template v-slot:tip>
									<div class="el-upload__tip">请上传文件，大小不超过200MB</div>
								</template>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submit">确定</el-button>
					<el-button @click="closeDialog">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { getResourceApi, addResourceApi, updateResourceApi, uploadResourceFileApi, deletePhysicalFileApi } from '@/api/resource';
import { ElMessage } from 'element-plus';
import { reactive, ref, unref } from 'vue';

const formRef = ref();

const props = defineProps({
	resourceTypeCode: {
		type: String,
		default: '',
	},
	typeList: {
		type: Array,
		default: () => [],
	},
});
const emits = defineEmits(['refresh']);

let form = ref({
	status: true,
	resourceTypeCode: unref(props.resourceTypeCode),
});

const getDetails = (id) => {
	getResourceApi(id).then((res) => {
		form.value = Object.assign({}, form.value, res);
	});
};

const rules = {
	name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
	version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
	resourceTypeCode: [{ required: true, message: '请选择资源所属类别', trigger: 'change' }],
	grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
	className: [{ required: true, message: '请输入班别', trigger: 'blur' }],
};

const handleUpload = async (options) => {
	const { file } = options;
	// 仅暂存文件对象，不上传
	form.value.file = file;
	return true;
};

const beforeUpload = (file) => {
	const isLt200M = file.size / 1024 / 1024 < 200;
	if (!isLt200M) {
		ElMessage.error('文件大小不能超过200MB');
	}
	return isLt200M;
};

const handleExceed = () => {
	ElMessage.warning('只能上传一个文件');
};

const submit = async () => {
	if (!formRef.value) return;

	await formRef.value.validate(async (valid) => {
		if (!valid) return;

		try {
			// 先保存基础记录获取ID
			let resourceId = dialogData.id;
			// 新增记录时先创建空记录
			if (!dialogData.id) {
				// console.log('新增资源请求参数:', form.value);
				const addRes = await addResourceApi({
					...form.value,
					filePath: null,
				}).catch((e) => {
					console.error('新增资源失败:', e);
					throw e;
				});
				// console.log('新增资源响应:', addRes);
				// 处理响应结构：兼容直接返回或包装在 data 对象中
				const resultData = addRes.data ? addRes.data : addRes;
				if (!resultData || !resultData.id) {
					throw new Error('新增记录失败：未获取到有效ID');
				}
				resourceId = resultData.id;
				dialogData.id = resourceId;
				form.value.id = resourceId;
				// console.log('生成的新ID:', resourceId);
			}

			// 编辑模式且更换文件时删除旧文件（保持原判断条件）
			if (dialogData.id && form.value.filePath && form.value.file) {
				await deletePhysicalFileApi(form.value.id);
			}

			// 分离文件上传和数据保存逻辑
			if (form.value.file) {
				// 文件上传逻辑
				const formData = new FormData();
				formData.append('file', form.value.file);
				formData.append('id', form.value.id || '');

				const uploadRes = await uploadResourceFileApi(formData);
				// 更新文件信息到资源记录
				await updateResourceApi({
					...form.value,
					...uploadRes.data,
				});
			} else if (dialogData.id) {
				// 无文件时更新已有记录
				await updateResourceApi(form.value);
			}

			ElMessage.success(dialogData.id ? '资源更新成功' : '资源创建成功');

			closeDialog();
			emits('refresh');
		} catch (error) {
			console.error('操作失败:', error);
			ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message));

			// 清理上传失败的文件
			if (form.value.file && !dialogData.id) {
				form.value.file = null;
			}
		}
	});
};

const dialogData = reactive({
	isShow: false,
	title: '新增',
	id: null,
});

// 打开弹框
const openDialog = async (row) => {
	dialogData.isShow = true;
	dialogData.title = '新增';
	if (row?.id) {
		dialogData.id = row.id;
		dialogData.title = '编辑';
		getDetails(row.id);
	} else if (row?.Code) {
		form.value.resourceTypeCode = unref(row.Code);
	}
};

const closeDialog = () => {
	dialogData.isShow = false;
	dialogData.id = null;
	form.value = {
		status: true,
		resourceTypeCode: unref(props.resourceTypeCode),
	};
};

defineExpose({
	openDialog,
});
</script>
<style scoped>
.upload-demo {
	width: 100%;
}
</style>
